package me.ilich.piet.interpreter;

import java.util.HashMap;
import java.util.Map;

public class Codel implements Colourable {
	
	private static final int FF = 255;
	private static final int C0 = 192;
	
	private static final int rgb(int r, int g, int b){
		return r*256*256 + g*256 + b;
	}
	
	private static final Map<Integer,Codel> sRGB = new HashMap<Integer, Codel>();
	static{
		sRGB.put(Integer.valueOf(rgb(FF, C0, 0)), instance(RED, LIGHT));
		sRGB.put(Integer.valueOf(rgb(FF, 0,  0)), instance(RED, NORMAL));
		sRGB.put(Integer.valueOf(rgb(C0, 0,  0)), instance(RED, DARK));
		
		sRGB.put(Integer.valueOf(rgb(FF, FF, C0)), instance(YELLOW, LIGHT));
		sRGB.put(Integer.valueOf(rgb(FF, FF, 0)), instance(YELLOW, NORMAL));
		sRGB.put(Integer.valueOf(rgb(C0, C0, 0)), instance(YELLOW, DARK));
		
		sRGB.put(Integer.valueOf(rgb(C0, FF, C0)), instance(GREEN, LIGHT));
		sRGB.put(Integer.valueOf(rgb( 0, FF, 0)), instance(GREEN, NORMAL));
		sRGB.put(Integer.valueOf(rgb( 0, C0, 0)), instance(GREEN, DARK));
		
		sRGB.put(Integer.valueOf(rgb(C0, FF, FF)), instance(CYAN, LIGHT));
		sRGB.put(Integer.valueOf(rgb( 0, FF, FF)), instance(CYAN, NORMAL));
		sRGB.put(Integer.valueOf(rgb( 0, C0, C0)), instance(CYAN, DARK));
		
		sRGB.put(Integer.valueOf(rgb(C0, C0, FF)), instance(BLUE, LIGHT));
		sRGB.put(Integer.valueOf(rgb( 0,  0, FF)), instance(BLUE, NORMAL));
		sRGB.put(Integer.valueOf(rgb( 0,  0, C0)), instance(BLUE, DARK));
		
		sRGB.put(Integer.valueOf(rgb(FF, C0, FF)), instance(MAGENTA, LIGHT));
		sRGB.put(Integer.valueOf(rgb(FF,  0, FF)), instance(MAGENTA, NORMAL));
		sRGB.put(Integer.valueOf(rgb(C0,  0, C0)), instance(MAGENTA, DARK));
		
		sRGB.put(Integer.valueOf(rgb(FF, FF, FF)), instanceWhite());
		sRGB.put(Integer.valueOf(rgb( 0,  0,  0)), instanceBlack());
	}
	
	public static Codel instance(int hue, int lightness){
		Codel c = new Codel();
		c.setHue(hue);
		c.setLightness(lightness);
		return c;
	}
	
	public static final Codel fromRGB(int r, int g, int b){
		Codel result = null;
		final int code = r*256*256 + g*256 + b;
		if(sRGB.containsKey(Integer.valueOf(code))){
			result = sRGB.get(Integer.valueOf(code));
		}else{
			result = instanceWhite();
		}
		return result;
	}
	
	public static Codel instanceWhite() {
		Codel c = new Codel();
		c.setHue(WHITE);
		return c;
	}
	
	
	public static Codel instanceBlack() {
		Codel c = new Codel();
		c.setHue(BLACK);
		return c;
	}
	
	private int mHue;
	private int mLightness;

	public int getColor() {
		return mHue;
	}

	@Override
	public int getHue() {
		return mHue;
	}
	
	public void setHue(int value) {
		mHue = value;
	}	

	@Override
	public int getLightness() {
		return mLightness;
	}
	
	public void setLightness(int value) {
		mLightness = value;
	}
	
	@Override
	public String toString() {
		return mHue + " " + mLightness;
	}

}
